import requests


class RequestTool:
    @staticmethod
    def request_def(url, method, params=None, data=None, headers=None, json=None):
        response = None
        if method == 'GET' or method == 'get':
            response = requests.get(url, params=params, headers=headers, json=json, data=data)
        elif method == 'POST' or method == 'post':
            response = requests.post(url, params=params, headers=headers, json=json, data=data)
        else:
            return "请求方式错误"

        if response is not None:
            rs = {}
            rs["status_code"] = response.status_code
            try:
                rs["data"] = response.json()
            except:
                rs["data"] = response.text
            rs["headers"] = response.headers
            rs["time"] = response.elapsed.total_seconds()
            return rs

    @classmethod
    def getToken(cls):
        login_json = {
            "password": "macro123",
            "username": "admin"
        }
        rs_login = cls.request_def("http://localhost:8080/admin/login", "post", json=login_json)
        token = rs_login.get("data").get("data").get("tokenHead") + rs_login.get("data").get("data").get("token")
        #  获取到通用授权请求头
        return {"Authorization": token}


if __name__ == '__main__':
    jsonData = {
        "password": "macro123",
        "username": "admin"
    }
    print(RequestTool.request_def("http://localhost:8080/admin/login", "post", json=jsonData))
